const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const dateFormatter = date => {
  // const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  return dateStr
}
const getDayOrderNo = async (event) => {
  const curDate = await dateFormatter(new Date())
  const queryResult = await db.collection("paymentDetails").where({chargeDate: curDate}).limit(1).orderBy("orderNo",'desc').get({})
  console.log('查询结果为：',queryResult,'查询日期为：',curDate)
  const data = queryResult.data
  if(data.length <=0 ){
    return {data: undefined, errMsg:'今日未生成订单'}
  }
  return { data: data[0],errMsg: '查询成功'}
}

const main = async (event)=>{
  return await getDayOrderNo()
}
module.exports = {
  main
}